#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/apps/sdk_management/utils.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
import os, shutil, string
from django.conf import settings
from jinja2 import Template
from apps.sdk_management.constants import COLLECTIONS_PY_TMPL, API_PY_TMPL, API_COMPONENT_TMPL

class SDKGenerator(object):

    def __init__(self, channels, target_dir=''):
        self.channels = channels
        self.target_dir = target_dir or self.get_tmp_dir()

    def get_target_dir(self):
        return self.target_dir

    def get_tmp_dir(self):
        return os.path.join('/tmp/open_paas_esb_sdk/')

    def generate_files_for_sdk(self):
        self.copy_tmpl_to_target_dir()
        self.generate_collections_py()
        self.generate_apis_files()

    def copy_tmpl_to_target_dir(self):
        source_dir = os.path.join(settings.BASE_DIR, 'apps/sdk_management/sdk_tmpl/')
        if os.path.exists(self.target_dir):
            shutil.rmtree(self.target_dir)
        shutil.copytree(source_dir, self.target_dir)
        if not os.path.exists(os.path.join(self.target_dir, 'blueking')):
            raise Exception(u'拷贝SDK模版到临时目录失败。')

    def generate_collections_py(self):
        content = self.get_collections_py_content()
        collections_py_path = os.path.join(self.target_dir, 'blueking/component/collections.py')
        self.write_content_to_file(content, collections_py_path)

    def generate_apis_files(self):
        for system_name, channels in self.channels.items():
            channels = sorted(channels, key=lambda item: item['path'])
            content = self.get_api_file_content(system_name, channels)
            api_file_path = os.path.join(self.target_dir, ('blueking/component/apis/{system_name}.py').format(system_name=system_name.lower()))
            self.write_content_to_file(content, api_file_path)

    def get_collections_py_content(self):
        import_collections = []
        available_collections = []
        for system_name in sorted(self.channels.keys()):
            system_name_lower = system_name.lower()
            system_name_smart = self.smart_system_name(system_name)
            import_collections.append(('from .apis.{system_name_lower} import Collections{system_name_smart}').format(system_name_lower=system_name_lower, system_name_smart=system_name_smart))
            available_collections.append(("    '{system_name_lower}': Collections{system_name_smart},").format(system_name_lower=system_name_lower, system_name_smart=system_name_smart))

        return Template(COLLECTIONS_PY_TMPL).render(import_collections=('\n').join(import_collections), available_collections=('\n').join(available_collections))

    def get_api_file_content(self, system_name, channels):
        apis = []
        for channel in channels:
            apis.append(API_COMPONENT_TMPL.format(api_name=channel['api_name'], api_path=channel['api_path'], suggest_method=channel['suggest_method'], api_description=channel['api_description'].encode('utf-8')))

        return Template(API_PY_TMPL).render(system_name_smart=self.smart_system_name(system_name), system_name=system_name, apis=('').join(apis).decode('utf-8'))

    def smart_system_name(self, system_name):
        if '_' in system_name:
            system_name = ('').join((string.capitalize(word) for word in system_name.split('_')))
        return system_name

    def write_content_to_file(self, content, file_path):
        if isinstance(content, str):
            content = content if 1 else content.encode('utf-8')
            with open(file_path, 'w') as (fp):
                fp.write(content)
            raise os.path.exists(file_path) or Exception(u'写入文件内容失败。')
